package com.ruoyi.jihuo.config;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 异步任务管理器
 * 通过任务ID实现多任务执行和取消
 */
@Slf4j
@Component
public class TaskManager {
    @Autowired
    private RedisCache redisCache;
    /**
     * key：任务ID，value：任务运行状态(true正常运行。false结束运行)
     */
    private final Map<String, AtomicBoolean> cancelFlags = new ConcurrentHashMap<>();

    /**
     * 注册任务
     * @param taskId
     */
    public void registerTask(String taskId) {
        cancelFlags.put(taskId, new AtomicBoolean(true));
        log.info("注册任务: {}", taskId);
    }

    /**
     * 取消任务
     * @param taskId
     */
    public void cancelTask(String taskId) {
        AtomicBoolean flag = cancelFlags.get(taskId);
        if (flag != null) {
            flag.set(false); // 设置取消标记
            log.info("取消任务: {}", taskId);
        }
    }

    /**
     * 检查任务是否已被取消。
     * @param taskId
     * @return
     */
    public boolean isCancelled(String taskId) {
        AtomicBoolean flag = cancelFlags.get(taskId);
        return flag != null && !flag.get();
    }

    /**
     * 移除任务
     * @param taskId
     */
    public void removeTask(String taskId) {
        cancelFlags.remove(taskId);
        redisCache.deleteObject((CacheConstants.TASK_INFO+"-"+taskId));
        redisCache.deleteObject((CacheConstants.TASK_PROGRESS+"-"+taskId));
        log.info("移除任务: {}", taskId);
    }
}
